﻿using Common;
using Configuration;
using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebSocket.Core
{
    public static class WebSocketManage
    {
        private static WebSocketServer Server;

        public static void StartServer()
        {
            try
            {
                var ip = Config.ServiceHost;
                var port = Config.ServiceWebSocketPort;
                Server = new WebSocketServer($"ws://{ip}:{port}");
                Server.Start(socket =>
                {
                    socket.OnClose = () => { HandleClose(socket); };
                    socket.OnError = (ex) => { HandleError(socket, ex); };
                    socket.OnOpen = () => { HandleOpen(socket); };
                });
            }
            catch (Exception ex)
            {
                Logger.Error($"WebSocket启动失败:{ex}");
            }
        }
        
        public static void StopServer()
        {
            Server?.Dispose();
        }

        /// <summary>
        /// 给所有客户端发消息
        /// </summary>
        /// <param name="obj"></param>
        public static void SendToAll(object obj)
        {
            var sessions = WebSocketDataManager.SocketUsers;
            foreach (var item in sessions)
                item.Value.Send(obj.ToJson());
        }

        /// <summary>
        /// 给指定客户端发消息
        /// </summary>
        public static void SendMessage(string token, object obj)
        {
            var session = WebSocketDataManager.GetSocketSession(token);
            session?.Send(obj.ToJson());
        }

        /// <summary>
        /// 断开指定的客户端
        /// </summary>
        public static void EndClient(string token)
        {
            var session = WebSocketDataManager.GetSocketSession(token);
            session?.Close();
        }

        private static void HandleError(IWebSocketConnection connection, Exception ex)
        {
            Logger.Error($"WebSocket服务发生错误:{ex}");
        }

        private static void HandleClose(IWebSocketConnection connection)
        {
            Logger.Error($"WebSocket服务已关闭！");
            WebSocketDataManager.RemoveUserSessionBySessionId(connection.ConnectionInfo.Id);
        }

        private static void HandleOpen(IWebSocketConnection connection)
        {
            Logger.Error($"WebSocket服务已打开！");
            WebSocketDataManager.AddUser($"{Guid.NewGuid()}", connection);
        }
    }
}
